<template>
  <view class="security-page">
    <!-- 顶部提示信息 -->
    <view class="security-header">
      <view class="security-header-icon">
        <up-icon name="lock" size="32" color="#2979ff"></up-icon>
      </view>
      <text class="security-header-title">账号安全</text>
      <text class="security-header-desc"
        >定期修改密码可以提高您的账号安全性</text
      >
    </view>

    <!-- 安全选项卡 -->
    <up-tabs :list="tabsList" :current="currentTab" @change="handleTabChange"></up-tabs>

    <!-- 密码修改表单 -->
    <view class="tab-content" v-if="currentTab === 0">
      <view class="password-form">
        <up-form
          :model="passwordForm"
          :rules="formRules"
          ref="passwordFormRef"
          labelPosition="left"
          labelWidth="90"
        >
          <view class="form-card">
            <up-form-item label="原密码" prop="oldPassword" :borderBottom="true">
              <up-input
                v-model="passwordForm.oldPassword"
                placeholder="请输入原密码"
                type="password"
                border="none"
              ></up-input>
            </up-form-item>

            <up-form-item label="新密码" prop="newPassword" :borderBottom="true">
              <up-input
                v-model="passwordForm.newPassword"
                placeholder="请输入新密码"
                type="password"
                border="none"
              ></up-input>
            </up-form-item>

            <up-form-item
              label="确认密码"
              prop="confirmPassword"
              :borderBottom="false"
            >
              <up-input
                v-model="passwordForm.confirmPassword"
                placeholder="请再次输入新密码"
                type="password"
                border="none"
              ></up-input>
            </up-form-item>
          </view>
        </up-form>

        <!-- 密码规则提示 -->
        <view class="password-tips">
          <view class="tips-title">密码要求:</view>
          <view class="tips-item">
            <up-icon name="checkmark-circle" size="14" color="#2979ff"></up-icon>
            <text>至少8个字符</text>
          </view>
          <view class="tips-item">
            <up-icon name="checkmark-circle" size="14" color="#2979ff"></up-icon>
            <text>包含大小写字母和数字</text>
          </view>
          <view class="tips-item">
            <up-icon name="checkmark-circle" size="14" color="#2979ff"></up-icon>
            <text>不能与旧密码相同</text>
          </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-section">
          <up-button type="primary" @click="changePassword">修改密码</up-button>
        </view>
      </view>
    </view>

    <!-- 两因素认证 -->
    <view class="tab-content" v-if="currentTab === 1">
      <view class="two-factor-section">
        <view class="security-card">
          <view class="security-card-header">
            <text class="security-card-title">两因素认证</text>
            <up-switch v-model="twoFactorEnabled" @change="toggleTwoFactor"></up-switch>
          </view>
          <view class="security-card-content">
            <text class="security-card-desc">启用两因素认证后，登录时需要输入额外的验证码，提高账号安全性。</text>
          </view>
        </view>

        <view class="security-card" v-if="twoFactorEnabled">
          <view class="security-card-header">
            <text class="security-card-title">验证方式</text>
          </view>
          <view class="security-card-content">
            <up-radio-group v-model="verificationMethod">
              <up-radio label="sms" name="sms">短信验证码</up-radio>
              <up-radio label="app" name="app" style="margin-top: 12px;">身份验证器应用</up-radio>
            </up-radio-group>
          </view>
        </view>

        <view class="security-card" v-if="twoFactorEnabled && verificationMethod === 'sms'">
          <view class="security-card-header">
            <text class="security-card-title">手机号码</text>
          </view>
          <view class="security-card-content">
            <up-input v-model="phoneNumber" placeholder="请输入手机号码"></up-input>
            <view class="verify-button-container">
              <up-button type="primary" size="small" @click="sendVerificationCode">发送验证码</up-button>
            </view>
          </view>
        </view>

        <view class="security-card" v-if="twoFactorEnabled && verificationMethod === 'app'">
          <view class="security-card-header">
            <text class="security-card-title">身份验证器</text>
          </view>
          <view class="security-card-content">
            <view class="qr-code-container">
              <image src="/static/qrcode-placeholder.png" mode="aspectFit" class="qr-code-image"></image>
            </view>
            <text class="security-card-desc">请使用 Google Authenticator 或其他身份验证器应用扫描上方二维码</text>
          </view>
        </view>

        <view class="save-section" v-if="twoFactorEnabled">
          <up-button type="primary" @click="saveTwoFactorSettings">保存设置</up-button>
        </view>
      </view>
    </view>

    <!-- 登录历史 -->
    <view class="tab-content" v-if="currentTab === 2">
      <view class="login-history-section">
        <view class="security-card">
          <view class="security-card-header">
            <text class="security-card-title">最近登录记录</text>
          </view>
          <view class="security-card-content">
            <view class="login-history-empty" v-if="loginHistory.length === 0">
              <up-icon name="info-circle" size="32" color="#909399"></up-icon>
              <text>暂无登录记录</text>
            </view>
            <view class="login-history-list" v-else>
              <view class="login-history-item" v-for="(item, index) in loginHistory" :key="index">
                <view class="login-history-item-left">
                  <up-icon :name="item.device === 'mobile' ? 'phone' : 'computer'" size="24" color="#2979ff"></up-icon>
                </view>
                <view class="login-history-item-right">
                  <view class="login-history-item-info">
                    <text class="login-device">{{ item.deviceName }}</text>
                    <text class="login-status" :class="item.status === 'success' ? 'success' : 'fail'">
                      {{ item.status === 'success' ? '成功' : '失败' }}
                    </text>
                  </view>
                  <view class="login-history-item-detail">
                    <text class="login-ip">IP: {{ item.ip }}</text>
                    <text class="login-time">{{ item.time }}</text>
                  </view>
                  <view class="login-history-item-location">
                    <up-icon name="map" size="14" color="#909399"></up-icon>
                    <text>{{ item.location }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { updateUserPassword, getUserSecuritySettings, updateUserSecuritySettings, getLoginHistory, sendSmsVerificationCode } from "@/api/user";

// 选项卡
const tabsList = [
  { name: '修改密码' },
  { name: '两因素认证' },
  { name: '登录历史' }
];
const currentTab = ref(0);

// 密码表单数据
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 表单验证规则
const formRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, message: "密码长度不能小于8个字符", trigger: "blur" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
      message: "密码必须包含大小写字母和数字",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.oldPassword) {
          callback(new Error("新密码不能与原密码相同"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 表单引用
const passwordFormRef = ref(null);

// 两因素认证数据
const twoFactorEnabled = ref(false);
const verificationMethod = ref('sms');
const phoneNumber = ref('');

// 登录历史
const loginHistory = ref([
  {
    device: 'mobile',
    deviceName: 'iPhone 13',
    status: 'success',
    ip: '192.168.1.1',
    time: '2023-05-15 14:30:22',
    location: '广东省广州市'
  },
  {
    device: 'computer',
    deviceName: 'Windows PC',
    status: 'success',
    ip: '192.168.1.100',
    time: '2023-05-14 09:15:43',
    location: '广东省广州市'
  },
  {
    device: 'mobile',
    deviceName: 'Android Device',
    status: 'fail',
    ip: '114.114.114.114',
    time: '2023-05-13 22:45:10',
    location: '浙江省杭州市'
  }
]);

// 页面加载时获取安全设置
onMounted(async () => {
  try {
    // 这里应该调用API获取用户安全设置
    // const res = await getUserSecuritySettings();
    // if (res.success) {
    //   twoFactorEnabled.value = res.data.twoFactorEnabled;
    //   verificationMethod.value = res.data.verificationMethod || 'sms';
    //   phoneNumber.value = res.data.phoneNumber || '';
    // }
    
    // 获取登录历史
    // const historyRes = await getLoginHistory();
    // if (historyRes.success) {
    //   loginHistory.value = historyRes.data;
    // }
  } catch (error) {
    console.error('获取安全设置失败', error);
  }
});

// 修改密码方法
async function changePassword() {
  if (!passwordFormRef.value) return;

  try {
    // 表单验证
    await passwordFormRef.value.validate();

    // 显示加载中
    uni.showLoading({
      title: "提交中...",
    });
    const res = await updateUserPassword({
      password: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });
    if (res.success) {
      // 隐藏加载
      uni.hideLoading();

      // 显示成功提示
      uni.showToast({
        title: "密码修改成功",
        icon: "success",
      });

      // 清空表单
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    } else {
      // 显示失败提示
      uni.showToast({
        title: res.message,
        icon: "none",
      });
      return;
    }
  } catch (error) {
    // 显示表单验证错误
    uni.showToast({
      title: "请检查输入项",
      icon: "none",
    });
  }
}

// 切换选项卡
function handleTabChange(index) {
  currentTab.value = index;
}

// 切换两因素认证
function toggleTwoFactor(value) {
  twoFactorEnabled.value = value;
}

// 发送验证码
async function sendVerificationCode() {
  if (!phoneNumber.value) {
    uni.showToast({
      title: '请输入手机号码',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: '发送中...'
    });
    
    const res = await sendSmsVerificationCode({
      phoneNumber: phoneNumber.value
    });
    
    uni.hideLoading();
    
    if (res.success) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: res.message || '发送失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: '发送失败',
      icon: 'none'
    });
  }
}

// 保存两因素认证设置
async function saveTwoFactorSettings() {
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    // 这里应该调用API保存两因素认证设置
    // const res = await updateUserSecuritySettings({
    //   twoFactorEnabled: twoFactorEnabled.value,
    //   verificationMethod: verificationMethod.value,
    //   phoneNumber: phoneNumber.value
    // });
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    uni.hideLoading();
    uni.showToast({
      title: '设置已保存',
      icon: 'success'
    });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  }
}
</script>

<style lang="scss" scoped>
.security-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40px;
}

/* 顶部提示信息 */
.security-header {
  background-color: #ffffff;
  padding: 24px 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.security-header-icon {
  width: 64px;
  height: 64px;
  background-color: #ecf5ff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 12px;
}

.security-header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.security-header-desc {
  font-size: 14px;
  color: #909399;
}

/* 选项卡内容 */
.tab-content {
  padding-top: 16px;
}

/* 表单区域 */
.password-form {
  padding: 0 12px;
}

.form-card {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 密码规则提示 */
.password-tips {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.tips-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.tips-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.tips-item text {
  margin-left: 8px;
  font-size: 13px;
  color: #606266;
}

/* 保存按钮 */
.save-section {
  padding: 20px 12px;
}

/* 两因素认证部分 */
.two-factor-section {
  padding: 0 12px;
}

.security-card {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 16px;
}

.security-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.security-card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.security-card-content {
  padding: 4px 0;
}

.security-card-desc {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.verify-button-container {
  margin-top: 12px;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  margin: 16px 0;
}

.qr-code-image {
  width: 180px;
  height: 180px;
}

/* 登录历史部分 */
.login-history-section {
  padding: 0 12px;
}

.login-history-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px 0;
  color: #909399;
}

.login-history-empty text {
  margin-top: 12px;
  font-size: 14px;
}

.login-history-list {
  padding: 8px 0;
}

.login-history-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f2f2f2;
}

.login-history-item:last-child {
  border-bottom: none;
}

.login-history-item-left {
  margin-right: 16px;
  display: flex;
  align-items: center;
}

.login-history-item-right {
  flex: 1;
}

.login-history-item-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.login-device {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
}

.login-status {
  font-size: 13px;
  padding: 2px 8px;
  border-radius: 10px;
}

.login-status.success {
  background-color: #ecf9eb;
  color: #67c23a;
}

.login-status.fail {
  background-color: #fef0f0;
  color: #f56c6c;
}

.login-history-item-detail {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.login-ip, .login-time {
  font-size: 13px;
  color: #909399;
}

.login-history-item-location {
  display: flex;
  align-items: center;
}

.login-history-item-location text {
  margin-left: 4px;
  font-size: 13px;
  color: #909399;
}

/* 响应式适配 */
@media screen and (max-width: 500px) {
  .password-form, .two-factor-section, .login-history-section {
    padding: 0 8px;
  }

  .security-header {
    padding: 20px 12px;
  }
}
</style>
